package study.spring.transaction;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcServiceTransaction {
	
	private Connection conn;
	
	private String driver="com.mysql.jdbc.Driver";
	private String url="jdbc:mysql://172.16.1.153/chouti_digg?useUnicode=true";
	private String pwd="chouti";
	private String user="chouti_digg";
	
	private Connection getConnection(){
		if(conn==null){
			try {
				Class.forName(driver);
				conn=DriverManager.getConnection(url, user, pwd);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return conn;
	}
	
	public void insert(){
		boolean flag=false;
		try {
			String sql="INSERT INTO tbl_chouti_edit_link (name,img_url,url) VALUES ('5', '/images/image48.png', 'http://www.baidu.com')";
			conn=getConnection();
			conn.setAutoCommit(false);    
			Statement st = conn.createStatement(); 
			int a=st.executeUpdate(sql);
			System.out.println("success:"+a);
			if(!flag){
				throw new Exception();
			}
		} catch (Exception e) {
			e.printStackTrace();
			
			try {
				conn.rollback();
				System.out.println("rollback");
			} catch (SQLException e1) {
				System.out.println("rollback failed");
				e1.printStackTrace();
			}
		}finally{
			try {
				conn.commit();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	 
	}
	
	public static void main(String[] args) {
		JdbcServiceTransaction transaction=new JdbcServiceTransaction();
		transaction.insert();
	}
}
